/*
 * user_beep.c
 *
 *  Created on: Jan 9, 2025
 *      Author: Lenovo
 */
#include "debug.h"
#include "user_config.h"
#include "user_tick_timer.h"
#include "user_beep.h"

static uint16_t s_u16BEEP_delay_temp = 0;
static uint16_t beep_off_delay = 0;


static uint16_t s_u16BEEP_n = 0;

static uint8_t beep_open_flag = 0;

static uint8_t is_beep_sleep = 1;

void beep_init(void) {
    GPIO_InitTypeDef GPIO_InitStructure = {0};

    RCC_PB2PeriphClockCmd(RCC_PB2Periph_GPIOA, ENABLE);

    GPIO_InitStructure.GPIO_Pin = BEEP_PIN;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(BEEP_PORT, &GPIO_InitStructure);

    //BEEP_ON();

   // Delay_Ms(200);
    BEEP_OFF();
}

void open_beep(uint16_t time_ms, uint16_t n)
{
#if 1
    if(is_beep_sleep == 0){
        return;
    }
    g_u16timer_delay[BEEP_DELAY] = time_ms;
    s_u16BEEP_delay_temp = time_ms;
    beep_off_delay = s_u16BEEP_delay_temp;
    s_u16BEEP_n = (n-1 << 1) + 1;
    //s_u16BEEP_n += 2 * n - 1;

    BEEP_ON();
    beep_open_flag = 1;
    is_beep_sleep = 0;
#else
    printf("beep on \r\n");
    BEEP_OFF();
    for(uint8_t i = 0; i< n; i++){
        BEEP_ON();
        Delay_Ms(time_ms);
        BEEP_OFF();
        Delay_Ms(time_ms);
    }
    printf("beep off \r\n");
#endif
}

void open_beep_with_off_delay(uint16_t time_ms, uint16_t off_delay, uint16_t n) {
#if 0
    BEEP_OFF();

    if (n == 0) {
        s_u16BEEP_n = 0;
    }
    else {
        s_u16BEEP_n = ( (n-1) << 1) + 1;
        //s_u16BEEP_n += 2 * n - 1;
    }
    s_u16BEEP_delay_temp = time_ms;

    if (s_u16BEEP_n > 0) {

        BEEP_ON();

        beep_off_delay = off_delay;
    }
    else {
        BEEP_OFF();
    }
#else

#endif

}

void beep_manage(void)
{
    if (s_u16BEEP_n != 0) {
        if (g_u16timer_delay[BEEP_DELAY] == 0) {

            s_u16BEEP_n--;
            if (beep_open_flag == 1) {
                BEEP_OFF();
                beep_open_flag = 0;
                g_u16timer_delay[BEEP_DELAY] = beep_off_delay;
            }
            else {
                BEEP_ON();
                beep_open_flag = 1;
                g_u16timer_delay[BEEP_DELAY] = s_u16BEEP_delay_temp;
            }
            //BEEP = ~BEEP;
        }
    }
    else {
        BEEP_OFF();
        beep_open_flag = 0;

        is_beep_sleep = 1;
    }
}

uint8_t get_is_beep_sleep(void){
    return is_beep_sleep;
}
